package com.dongnao.network.netty_packet;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;

public class NettyServerHandler extends SimpleChannelInboundHandler<ByteBuf> {

    private int count;

    //读取数据
    /*
    1. ChannelHandlerContext ctx:上下文对象，含有管道pipeline，通道channel，地址
    2. Object msg:就是客户端发送的数据，默认 Object
    */
    @Override
    public void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) {
        byte[] buffer = new byte[msg.readableBytes()];
        msg.readBytes(buffer);
        String message = new String(buffer, Charset.forName("utf-8"));
        System.out.println("接收到消息=" + message);
        System.out.println("接收消息数量=" + (++this.count));

        //服务器会送一个数据给客户端
        ctx.writeAndFlush(Unpooled.copiedBuffer("我收到你的数据啦", Charset.forName("utf-8")));
    }

    //异常处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }

}
